<?php
class model_redis
{
	private $redis;
	
	private $redis_host;
	
	private $redis_port;
	
	private $redis_timeout;
	
	public function __construct($host, $port, $timeout = 0)
	{
		$this->redis_host = $host;
		
		$this->redis_port = $port;
		
		$this->redis_timeout = $timeout;
		
		$this->connect();
	}
	
	/**
	 * 连接redis服务器
	 */
	private function connect()
	{		
		$this->redis = new redis();
		
		$this->redis->connect($this->redis_host, $this->redis_port, $this->redis_timeout);

		return $this->redis;
	}
	
	/**
	 * 切换到指定数据库
	 * @param $index
	 */
	public function redis_select($index)
	{
		return $this->redis->select($index);
	}
	
	/**
	 * 将字符串值value关联到key中
	 * 如果key中已存在值，则用value覆写
	 * @param $key
	 * @param $value
	 * @return bool
	 */
	public function redis_set($key, $value)
	{
		return $this->redis->set($key, $value);
	}
	
	/**
	 * 当key不存在是将其设置为value
	 * @param $key
	 * @param $value
	 */
	public function redis_setnx($key, $value)
	{
		return $this->redis->setnx($key, $value);
	}
	
	/**
	 * 返回key所关联的字符串值
	 * @param $key
	 * @return $value
	 */
	public function redis_get($key)
	{
		$value = $this->redis->get($key);
		
		return $value;
	}
	
	/**
	 * 将value写入列表key中
	 * @param $key
	 * @param $value
	 * @param $right 表头或表尾
	 */
	public function redis_push($key, $value, $right = true)
	{
		return $right ? $this->redis->rPush($key, $value) : $this->redis->lPush($key, $value);
	}
	
	/**
	 * 移除并返回列表key中的头元素或尾元素
	 * @param $key
	 * @param $left
	 */
	public function redis_pop($key, $left = true)
	{
		return $left ? $this->redis->lPop($key) : $this->redis->rPop($key);
	}
	
	/**
	 * 将KEY中存储的值自增1
	 * @param $key
	 * @return bool
	 */
	public function redis_increment($key)
	{
		return $this->redis->incr($key);
	}
	
	/**
	 * 将KEY中存储的值自减1
	 * @param $key
	 * @return bool
	 */
	public function redis_decrement($key)
	{
		return $this->redis->decr($key);
	}
	
	/**
	 * 检测指定的key是否存在
	 * @param $key
	 * @return bool
	 */
	public function redis_exists($key)
	{
		return $this->redis->exists($key);
	}
	
	/**
	 * 移除给定的一个或多个key
	 * 如果key不存在，则忽略
	 * @param $key
	 */
	public function redis_delete($key)
	{
		return $this->redis->delete($key);
	}
	
	/**
	 * 清空整个redis服务器的数据
	 */
	public function redis_flushall()
	{
		return $this->redis->flushAll();
	}
	
	/**
	 * 返回redis对象
	 */
	public function _redis()
	{
		return $this->redis;
	}
}
